<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px" class="advanced-search-form">
      <el-row :gutter="15">
        <!-- First row -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商户id" prop="storeInfoId">
            <el-input
                v-model="queryParams.storeInfoId"
                placeholder="请输入关联商户信息表ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商品SKU ID" prop="skuId">
            <el-input
                v-model="queryParams.skuId"
                placeholder="请输入商品SKU ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="变动类型" prop="changeType">
            <el-select
                v-model="queryParams.changeType"
                placeholder="请选择变动类型"
                clearable
                style="width: 100%; min-width: 200px"
            >
              <el-option
                  v-for="dict in stock_change_log_change_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="变动数量" prop="changeQuantity">
            <el-input
                v-model="queryParams.changeQuantity"
                placeholder="请输入变动数量"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- Second row -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="变更前库存" prop="beforeQuantity">
            <el-input
                v-model="queryParams.beforeQuantity"
                placeholder="请输入变更前库存"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="变更后库存" prop="afterQuantity">
            <el-input
                v-model="queryParams.afterQuantity"
                placeholder="请输入变更后库存"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="业务来源ID" prop="referenceId">
            <el-input
                v-model="queryParams.referenceId"
                placeholder="请输入业务来源ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="操作人ID" prop="operatorId">
            <el-input
                v-model="queryParams.operatorId"
                placeholder="请输入操作人ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- Third row -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="备注说明" prop="remark">
            <el-input
                v-model="queryParams.remark"
                placeholder="请输入备注说明"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="逻辑删除标志" prop="delFlag">
            <el-select
                v-model="queryParams.delFlag"
                placeholder="请选择逻辑删除标志"
                clearable
                style="width: 100%; min-width: 200px"
            >
              <el-option
                  v-for="dict in del_flag"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- Action buttons -->
      <el-row>
        <el-col :span="24" style="text-align: right; padding-right: 10px;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['core:StockChangeLog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['core:StockChangeLog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['core:StockChangeLog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['core:StockChangeLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="StockChangeLogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="商户" align="center">
        <template #default="scope">
          <span>{{ scope.row.storeInfoId }}-{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SKU ID" align="center" prop="skuId" />
      <el-table-column label="变动类型" align="center" prop="changeType">
        <template #default="scope">
          <dict-tag :options="stock_change_log_change_type" :value="scope.row.changeType"/>
        </template>
      </el-table-column>
      <el-table-column label="变动数量" align="center" prop="changeQuantity" />
      <el-table-column label="变更前库存" align="center" prop="beforeQuantity" />
      <el-table-column label="变更后库存" align="center" prop="afterQuantity" />
      <el-table-column label="业务来源ID" align="center" prop="referenceId" />
      <el-table-column label="操作人ID" align="center" prop="operatorId" />
      <el-table-column label="备注说明" align="center" prop="remark" />
      <el-table-column label="逻辑删除标志" align="center" prop="delFlag">
        <template #default="scope">
          <el-tag
              :type="scope.row.delFlag === '0' ? 'success' : 'danger'"
              :effect="scope.row.delFlag === '0' ? 'light' : 'plain'"
          >
            <dict-tag :options="del_flag" :value="scope.row.delFlag"/>
          </el-tag>

        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['core:StockChangeLog:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['core:StockChangeLog:remove']">删除</el-button>
          <el-button link type="success" icon="Refresh" @click="handleRecover(scope.row)" v-hasPermi="['core:StockLockRecord:edit']">
            误删恢复
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存变动日志对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="StockChangeLogRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商户" prop="storeInfoId">
          <el-select
              v-model="form.storeInfoId"
              placeholder="请选择商户"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="store in storeOptions"
                :key="store.id"
                :label="`${store.id}-${store.name}`"
                :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品SKU ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入商品SKU ID" />
        </el-form-item>
        <el-form-item label="变动类型" prop="changeType">
          <el-select v-model="form.changeType" placeholder="请选择变动类型">
            <el-option
              v-for="dict in stock_change_log_change_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变动数量" prop="changeQuantity">
          <el-input v-model="form.changeQuantity" placeholder="请输入变动数量" />
        </el-form-item>
        <el-form-item label="变更前库存" prop="beforeQuantity">
          <el-input v-model="form.beforeQuantity" placeholder="请输入变更前库存" />
        </el-form-item>
        <el-form-item label="变更后库存" prop="afterQuantity">
          <el-input v-model="form.afterQuantity" placeholder="请输入变更后库存" />
        </el-form-item>
        <el-form-item label="业务来源ID" prop="referenceId">
          <el-input v-model="form.referenceId" placeholder="请输入业务来源ID" />
        </el-form-item>
        <el-form-item label="操作人ID" prop="operatorId">
          <el-input v-model="form.operatorId" placeholder="请输入操作人ID" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" />
        </el-form-item>
        <el-form-item label="逻辑删除标志" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除标志">
            <el-option
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StockChangeLog">
import { listStockChangeLog, getStockChangeLog, delStockChangeLog, addStockChangeLog, updateStockChangeLog } from "@/api/core/StockChangeLog"
import {listStoreInfo , getStoreInfo} from "@/api/core/storeInfo.js";
const { proxy } = getCurrentInstance()
const { stock_change_log_change_type, del_flag } = proxy.useDict('stock_change_log_change_type', 'del_flag')

const StockChangeLogList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeInfoId: null,
    skuId: null,
    changeType: null,
    changeQuantity: null,
    beforeQuantity: null,
    afterQuantity: null,
    referenceId: null,
    operatorId: null,
    remark: null,
    delFlag: 0,
  },
  rules: {
    storeInfoId: [
      { required: true, message: "关联商户信息表id不能为空", trigger: "blur" }
    ],
    skuId: [
      { required: true, message: "商品SKU ID不能为空", trigger: "blur" }
    ],
    changeType: [
      { required: true, message: "变动类型不能为空", trigger: "change" }
    ],
    changeQuantity: [
      { required: true, message: "变动数量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 在响应式变量部分添加
const storeOptions = ref([]); // 存储商户选项

// 在methods部分添加获取商户列表的方法
function getStoreOptions() {
  listStoreInfo({
    pageNum: 1,
    pageSize: 1000  // 设置足够大的pageSize获取所有商户
  }).then(response => {
    storeOptions.value = response.rows;
  });
}

// 在created/mounted生命周期中调用
onMounted(() => {
  getStoreOptions();
});

/** 查询库存变动日志列表 */
function getList() {
  loading.value = true;
  listStockChangeLog(queryParams.value).then(response => {
    StockChangeLogList.value = response.rows;
    total.value = response.total;

    // 获取所有商户信息并关联到表格数据
    const storeIds = [...new Set(response.rows.map(item => item.storeInfoId))];
    if (storeIds.length > 0) {
      listStoreInfo({ ids: storeIds.join(',') }).then(storeResponse => {
        const storeMap = new Map();
        storeResponse.rows.forEach(store => {
          storeMap.set(store.id, store);
        });

        // 将商户名称合并到交易记录中
        StockChangeLogList.value = response.rows.map(record => {
          return {
            ...record,
            name: storeMap.get(record.storeInfoId)?.name || '未知商户'
          };
        });
      }).finally(() => {
        loading.value = false;
      });
    } else {
      loading.value = false;
    }
  }).catch(() => {
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeInfoId: null,
    skuId: null,
    changeType: null,
    changeQuantity: null,
    beforeQuantity: null,
    afterQuantity: null,
    referenceId: null,
    operatorId: null,
    remark: null,
    delFlag: 0,
    createTime: null
  }
  proxy.resetForm("StockChangeLogRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加库存变动日志"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStockChangeLog(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改库存变动日志"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["StockChangeLogRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStockChangeLog(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStockChangeLog(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
// function handleDelete(row) {
//   const _ids = row.id || ids.value
//   proxy.$modal.confirm('是否确认删除库存变动日志编号为"' + _ids + '"的数据项？').then(function() {
//     return delStockChangeLog(_ids)
//   }).then(() => {
//     getList()
//     proxy.$modal.msgSuccess("删除成功")
//   }).catch(() => {})
// }
/** 删除按钮操作 - 改为逻辑删除 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认将库存变更日志编号为"' + _ids + '"的数据项设为删除状态？').then(function() {
    // 改为调用更新状态的API
    return updateStockChangeLog({ id: _ids, delFlag: '1' })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("操作成功")
  }).catch(() => {})
}
/** 恢复按钮操作 */
function handleRecover(row) {
  const _id = row.id
  proxy.$modal.confirm('是否确认恢复库存变更日志编号为"' + _id + '"的数据项？').then(function() {
    return updateStockChangeLog({ id: _id, delFlag: '0' })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('core/StockChangeLog/export', {
    ...queryParams.value
  }, `StockChangeLog_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.advanced-search-form {
  padding: 18px 10px 0 10px;
  background: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 15px;
}
.advanced-search-form .el-form-item {
  margin-bottom: 15px;
}
</style>